#include "fileLoader.h"
#include <fstream>
/*
Copyright (C) <2011>  <ivan vaccari>

    <ivan.vaccari@studenti.unipr.it>


This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.


*/
#include <iostream>
#include "turingConfiguration.h"
#include "turingMachine.h"
fileLoader::fileLoader(turingConfiguration & _cfg, turingMachine & _mac):cfg(_cfg),mac(_mac){

}
bool fileLoader::loadConfigurationFromFile(const std::string & fname){

    std::ifstream f(fname.c_str());
    bool required1=false;
    bool required2=false;
    cfg.setName(fname);
    if (f.good()){
        while(!f.eof()){
            std::string line;
            getline(f,line);

            if(0==line.find("[instructions]")){
                required1=true;
                while(!f.eof()){
                    getline(f,line);
                    if(0==line.find("#")){
                        //do nothing
                    }else if(0==line.find("[/instructions]")){
                        break;
                    }else{
                        cfg.addInstruction(line);
                    }

                }
            }else if(0==line.find("first-symbol=")){
                required2=true;
                mac.setFirstSymbol(line.substr(13));
            }else if(0==line.find("tape-left=")){
                mac.setTapeLeft(line.substr(10));
            }else if(0==line.find("tape-right=")){
                mac.setTapeRight(line.substr(11));
            }else if(0==line.find("initial-state=")){
                cfg.setInitialState(line.substr(14));
            }else if(0==line.find("name=")){
                cfg.setName(line.substr(5));
            }else if(0==line.find("verbose=true")){
                mac.setVerbose(true);
            }else if(0==line.find("#")){
                //do nothing
            }
        }

        mac.setConfiguration(cfg);

        if (!required1)
            throw "No instruction section found.";
        if (!required2)
            throw "No first symbol declared.";

        return required1&&required2;
    }else{
        throw "Cannot load configuration file: "+fname;
        return false;
    }
}
